package com.example.understandvideo.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FFmpegFrameExtractor {

    public static void main(String[] args) {
        String inputFile = "D:\\home\\work\\rivulet-dawn\\2025-04-18\\0000000247358626.mp4";
        String outputPath = "D:\\home\\work\\rivulet-dawn\\thumbnail\\2025-04-18\\0000000247358626\\"; // 修改后缀可改变输出格式
        String timePoint = "00:00:00.000"; // 支持毫秒精度
        int quality = 2; // 仅对JPEG有效（2-31）

//        String[] command = {
//                "D:\\Environment\\ffmpeg-7.0.2-full_build\\bin\\ffmpeg.exe",
//                "-ss", timePoint,
//                "-i", inputFile,
//                "-vframes", "1",
//                "-q:v", String.valueOf(quality),
//                outputPath
//        };
        // 示例：每隔5秒抽取一帧
        String[] command = {
                "D:\\Environment\\ffmpeg-7.0.2-full_build\\bin\\ffmpeg.exe",
                "-i", inputFile,
                "-vf", "fps=1,scale=120:-1",// 每5秒一帧
                outputPath+"frame_%04d.png"
        };

        executeFFmpegCommand(command);

        File file= new File(outputPath);
        for(File kid :file.listFiles()){
            System.out.println(kid.getAbsolutePath());
        }
    }

    private static void executeFFmpegCommand(String[] command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            // 读取错误流（FFmpeg的输出通常通过错误流返回）
            BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream()));

            String line;
            StringBuilder output = new StringBuilder();
            while ((line = errorReader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 设置超时时间（毫秒）
            if (process.waitFor(60, TimeUnit.SECONDS)) {
                process.destroy();
            }
            errorReader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}